export default {
  transcodeIntervalMap: {},
  taskIdUserDataMap: {},
  instance: null,

  getInstance() {
    if (!this.instance) {
      this.instance = window.axios.create({
        baseURL: "https://edu-cf-1328602399.cos.ap-nanjing.myqcloud.com",
        // baseURL: 'https://tiw-3gflb4tn0d7f550f-1259648581.ap-shanghai.app.tcloudbase.com',
        timeout: 5000,
      });
    }
    return this.instance;
  },

  createTranscodeTask({ Url, IsStaticPPT }, callback) {
    this.getInstance()
      .post("/tiw_transcode", {
        cmd: "createTask",
        content: {
          SdkAppId: 1400127140,
          Url,
          IsStaticPPT,
          ThumbnailResolution: "200x200",
        },
      })
      .then((res) => {
        if (res.data.Error) {
          callback({
            code: res.data.Error.Code,
            message: res.data.Error.Message,
            status: "ERROR",
          });
        } else {
          const taskId = res.data.TaskId;
          this.transcodeIntervalMap[taskId] = setInterval(() => {
            // 查询进度
            this.describeTranscodeTask(taskId, callback);
          }, 5000);
          this.taskIdUserDataMap[taskId] = {};
        }
      })
      .catch((err) => {
        callback({
          status: "ERROR",
          code: "FailedOperation.SdkModule",
          message: `upload file failure, ${err.message}`,
        });
      });
  },

  describeTranscodeTask(taskId, callback) {
    this.getInstance()
      .post("/tiw_transcode", {
        cmd: "describeTask",
        content: {
          SdkAppId: 1400127140,
          TaskId: taskId,
        },
      })
      .then((res) => {
        if (res.data.Error) {
          callback({
            status: "ERROR",
            code: res.data.Error.Code,
            message: res.data.Error.Message,
            taskId,
            userData: this.taskIdUserDataMap[taskId],
            fileData: {},
          });
          clearInterval(this.transcodeIntervalMap[taskId]);
        } else {
          callback({
            status: "SUCCESS",
            code: 0,
            message: "",
            taskId,
            userData: this.taskIdUserDataMap[taskId],
            fileData: res.data,
          });
          if (res.data.Status === "FINISHED") {
            clearInterval(this.transcodeIntervalMap[taskId]);
          }
        }
      })
      .catch((err) => {
        callback({
          status: "ERROR",
          code: "FailedOperation.SdkModule",
          message: `transcode failure, ${err.message}`,
          taskId,
          userData: this.taskIdUserDataMap[taskId],
          fileData: {},
        });
        clearInterval(this.transcodeIntervalMap[taskId]);
      });
  },
};
